package com.xcode.example.modules.html2img.controller;

import com.xcode.example.base.BaseController;
import com.xcode.example.common.result.AjaxResult;
import com.xcode.example.common.utils.PhantomTools;
import com.xcode.example.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

/**
 * 网页转图片
 * 方式1：通过phantomjs在服务端实现网页渲染和截图
 * 方式2：通过H5 canvas在客户端实现网页转图片（未实现）
 * @author Administrator
 */
@Slf4j
@Controller
@RequestMapping("/html2img")
public class Html2ImgController extends BaseController {

    /**
     * 页面
     * @return 页面
     */
    @RequestMapping("/demo")
    public String demo() {
        return "html2img/html2img";
    }

    /**
     * 通过phantom生成百度网页截图
     * @return 截图访问路径
     */
    @RequestMapping("/printByPhantom")
    @ResponseBody
    public AjaxResult printByPhantom() {
        try {
            String url = "https://www.baidu.com";
            String filePath = AppConfig.getUploadPath();
            String hash = UUID.randomUUID().toString();
            String fileName = hash + ".jpg";
            PhantomTools phantomTools = new PhantomTools(filePath, hash);
            byte[] bytes = phantomTools.getByteImg(url);
            if (bytes != null && bytes.length > 0) {
                String imgPath = uploadFile(bytes, filePath, fileName);
                if (StringUtils.isNotBlank(imgPath)) {
                    return AjaxResult.success().put("imgPath", imgPath);
                } else {
                    return AjaxResult.error("生成图片文件失败");
                }
            } else {
                return AjaxResult.error("读取网页失败");
            }
        } catch(Exception e) {
            log.error("生成图片失败：" + e.getMessage());
            if (log.isDebugEnabled()) {
                e.printStackTrace();
            }

            return AjaxResult.error("生成图片失败：{}", e.getMessage());
        }
    }
}
